import { FlowiseConfig } from '@/types';

export class FlowiseClient {
  private config: FlowiseConfig;

  constructor(config: FlowiseConfig) {
    this.config = config;
  }

  // 获取请求头
  private getHeaders(): Record<string, string> {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    };

    if (this.config.apiKey) {
      headers['Authorization'] = `Bearer ${this.config.apiKey}`;
    }

    return headers;
  }

  // 发送预测请求
  async predict(question: string, overrideConfig?: any): Promise<any> {
    const response = await fetch(
      `${this.config.apiUrl}/api/v1/prediction/${this.config.chatflowId}`,
      {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify({
          question,
          overrideConfig,
        }),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Flowise API 错误: ${response.status} - ${errorText}`);
    }

    return response.json();
  }

  // 获取聊天消息
  async getChatMessages(sessionId?: string): Promise<any[]> {
    const url = sessionId 
      ? `${this.config.apiUrl}/api/v1/chatmessage/${this.config.chatflowId}?sessionId=${sessionId}`
      : `${this.config.apiUrl}/api/v1/chatmessage/${this.config.chatflowId}`;

    const response = await fetch(url, {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取聊天消息失败: ${response.status} - ${errorText}`);
    }

    return response.json();
  }

  // 获取聊天流程信息
  async getChatflow(): Promise<any> {
    const response = await fetch(
      `${this.config.apiUrl}/api/v1/chatflows/${this.config.chatflowId}`,
      {
        method: 'GET',
        headers: this.getHeaders(),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取聊天流程失败: ${response.status} - ${errorText}`);
    }

    return response.json();
  }

  // 获取所有聊天流程
  async getAllChatflows(): Promise<any[]> {
    const response = await fetch(
      `${this.config.apiUrl}/api/v1/chatflows`,
      {
        method: 'GET',
        headers: this.getHeaders(),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取聊天流程列表失败: ${response.status} - ${errorText}`);
    }

    return response.json();
  }

  // 删除聊天消息
  async deleteChatMessage(messageId: string): Promise<void> {
    const response = await fetch(
      `${this.config.apiUrl}/api/v1/chatmessage/${messageId}`,
      {
        method: 'DELETE',
        headers: this.getHeaders(),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`删除聊天消息失败: ${response.status} - ${errorText}`);
    }
  }

  // 获取分析数据
  async getAnalytics(startDate?: string, endDate?: string): Promise<any> {
    const params = new URLSearchParams();
    if (startDate) params.append('startDate', startDate);
    if (endDate) params.append('endDate', endDate);

    const response = await fetch(
      `${this.config.apiUrl}/api/v1/analytics?${params.toString()}`,
      {
        method: 'GET',
        headers: this.getHeaders(),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取分析数据失败: ${response.status} - ${errorText}`);
    }

    return response.json();
  }

  // 健康检查
  async healthCheck(): Promise<boolean> {
    try {
      const response = await fetch(`${this.config.apiUrl}/api/v1/ping`, {
        method: 'GET',
        headers: this.getHeaders(),
      });
      return response.ok;
    } catch {
      return false;
    }
  }
}

// 创建默认的 Flowise 客户端实例
export const createFlowiseClient = (): FlowiseClient => {
  const config: FlowiseConfig = {
    apiUrl: process.env.FLOWISE_API_URL || 'http://localhost:3001',
    apiKey: process.env.FLOWISE_API_KEY,
    chatflowId: process.env.FLOWISE_CHATFLOW_ID || '',
  };

  return new FlowiseClient(config);
};
